import React, { Fragment, useEffect } from "react";
import styles from "./SingInForm.module.scss";
import { useTranslation } from "react-i18next";
import { Form, Input, Button, Checkbox } from "antd";
import { userProduct } from "../../redux/user/userSlice";
import { useDispatch } from "react-redux";
import { useSelector } from "../../redux/hooks";
import { useHistory } from "react-router-dom";
export const SingInForm: React.FC = () => {
  const history = useHistory();
  const dispatch = useDispatch();
  const loading = useSelector((s) => s.user.loading);
//   const error = useSelector((s) => s.user.error);
  const jwt = useSelector((s) => s.user.token);
  const { t } = useTranslation();
  const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
  };
  const tailLayout = {
    wrapperCol: { offset: 8, span: 16 },
  };
  const onFinish = (values: {
    username: string | null;
    password: string | null;
  }) => {
    console.log("Success:", values);
    if (
      typeof values.username === "string" &&
      typeof values.password === "string"
    ) {
      dispatch(
        userProduct({
          email: values.username,
          password: values.password,
        })
      );
    }
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };
  useEffect(() => {
    if (jwt) {
        history.push("/");
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [jwt]);

  return (
    <Fragment>
      <Form
        {...layout}
        name="basic"
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        className={styles["register-form"]}
      >
        <Form.Item
          label={t("form.username")}
          name="username"
          hasFeedback
          rules={[{ required: true, message: t("form.username_message") }]}
        >
          <Input placeholder="请输入账户名/邮箱地址" />
        </Form.Item>

        <Form.Item
          label={t("form.userpassword")}
          name="password"
          hasFeedback
          rules={[{ required: true, message: t("form.userpassword_message") }]}
        >
          <Input.Password placeholder="请输入密码" />
        </Form.Item>

        <Form.Item {...tailLayout} name="remember" valuePropName="checked">
          <Checkbox>{t("form.remember_me")}</Checkbox>
        </Form.Item>

        <Form.Item {...tailLayout}>
          <Button type="primary" htmlType="submit" loading={loading}>
            {t("form.login")}
          </Button>
        </Form.Item>
      </Form>
    </Fragment>
  );
};
